using Microsoft.AspNetCore.Mvc;
using Scheduling.Api.Read.Services;

namespace Scheduling.Api.Read.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class XunfeiController : ControllerBase
    {
        private readonly IXunfeiService _xunfeiService;
        private readonly ILogger<XunfeiController> _logger;

        public XunfeiController(IXunfeiService xunfeiService, ILogger<XunfeiController> logger)
        {
            _xunfeiService = xunfeiService;
            _logger = logger;
        }

        /// <summary>
        /// 发送消息到讯飞AI（HTTP API）
        /// </summary>
        /// <param name="message">用户消息</param>
        /// <returns>AI回复</returns>
        [HttpPost("chat")]
        public async Task<IActionResult> Chat([FromBody] ChatRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Message))
                {
                    return BadRequest(new { error = "消息内容不能为空" });
                }

                var response = await _xunfeiService.SendMessageAsync(request.Message);
                return Ok(new { message = response });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "讯飞AI聊天失败");
                return StatusCode(500, new { error = "AI服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 发送消息到讯飞AI（WebSocket）
        /// </summary>
        /// <param name="message">用户消息</param>
        /// <returns>AI回复</returns>
        [HttpPost("chat-websocket")]
        public async Task<IActionResult> ChatWebSocket([FromBody] ChatRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Message))
                {
                    return BadRequest(new { error = "消息内容不能为空" });
                }

                var response = await _xunfeiService.SendMessageWebSocketAsync(request.Message);
                return Ok(new { message = response });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "讯飞AI WebSocket聊天失败");
                return StatusCode(500, new { error = "AI服务暂时不可用，请稍后重试" });
            }
        }

        /// <summary>
        /// 获取WebSocket连接URL
        /// </summary>
        /// <returns>WebSocket连接URL</returns>
        [HttpGet("websocket-url")]
        public async Task<IActionResult> GetWebSocketUrl()
        {
            try
            {
                var url = await _xunfeiService.GetWebSocketUrlAsync();
                return Ok(new { websocketUrl = url });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取WebSocket URL失败");
                return StatusCode(500, new { error = "获取WebSocket连接信息失败" });
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok(new { status = "healthy", service = "Xunfei AI Service" });
        }
    }

    public class ChatRequest
    {
        public string Message { get; set; } = string.Empty;
    }
}
